package com.kele.shiro.controller;

import com.kele.shiro.entity.User;
import com.kele.shiro.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
@RequestMapping("/user")
public class UserController {

	@Autowired
	UserService userService;

	@RequestMapping("/login")
//    @ResponseBody
	public String login(String username,String password,boolean rememberMe){
		// shiro登录api
		final Subject subject = SecurityUtils.getSubject();
		final UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(username, password,rememberMe);
		subject.login(usernamePasswordToken);

		return "redirect:/home.html";
	}

	@RequestMapping("/logout")
	public String logout(){
		Subject subject = SecurityUtils.getSubject();
		subject.logout();
		return "redirect:/login.html";
	}

	/**
	 * 用户注册
	 */
	@RequestMapping("/register")
	public String register( User user) {
		try {
			userService.register(user);
			return "redirect:/login.html";
		}catch (Exception e){
			e.printStackTrace();
			return "redirect:/register.html";
		}
	}
}
